import json
import os
import openpyxl
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet


class DoFile:
    """文件操作类"""

    def __init__(self, base_path=None):
        self.my_path = base_path or r"E:\pythonworkspace\autoOne\datas"

    def doReed(self):
        """读取文件"""
        filename = r"E:\pythonworkspace\autoOne\datas\jiaYunSuan.xlsx"

        with open(filename, encoding="utf-8") as f:
            print(f, type(f))
            print(f.read())

    def doTxtWrite(self):
        """写入txt文件"""
        fileName = r"E:\pythonworkspace\pyBase\myDatas\myFile.txt"
        with open(fileName, mode='a', encoding="utf-8") as f:
            f.write("\n新内容")

    def pngRead(self):
        """读取图片"""
        fileName = r"E:\pythonworkspace\pyBase\myDatas\pic.jpg"
        with open(fileName, mode='rb') as f:
            myPng = f.read()
            return myPng

    def pngWrite(self, fname, strs):
        """写入图片"""
        fileName = rf"E:\pythonworkspace\pyBase\myDatas\{fname}"
        with open(fileName, mode='wb') as f:
            f.write(strs)

    def doDictToJsonStr(self, d):
        """字典转换成json格式的字符串"""
        s = json.dumps(d, ensure_ascii=False)
        print(s, type(s))
        return s

    def doJsonToDictStr(self, jsonS):
        """json格式的字符串转成字典"""
        d = json.loads(jsonS)
        print(d, type(d))
        return d

    def doDictToJsonFile(self, d, fname):
        """字典中内容保存成功json格式文件"""
        filename = os.path.join(self.my_path, fname)
        with open(filename, mode='w', encoding="utf-8") as f:
            json.dump(d, f, ensure_ascii=False, indent=4)

    def doJsonToDictFile(self, fname):
        """json格式文件提取出并转成字典"""
        fileName = os.path.join(self.my_path, fname)
        with open(fileName, mode='r', encoding='utf-8') as f:
            d = json.load(f)
            print(d, type(d))
            return d

    def doExcelReadDIV(self, fname, stname=None, minRow=1, maxRow=None, minCol=1, maxCol=None):
        """处理EXCEL文件，读取数据"""
        filename = os.path.join(self.my_path, fname)
        wk = None

        try:
            wk = openpyxl.load_workbook(filename)  # 加载工作簿
            if stname is None:
                stname = wk.sheetnames[0]  # 默认第一个工作表

            st = wk[stname]  # 获取工作表
            print(f"工作表: {st}, 类型: {type(st)}")

            # 提取部分数据
            ss = st.iter_rows(
                min_row=minRow,
                max_row=maxRow,
                min_col=minCol,
                max_col=maxCol,
                values_only=True
            )

            l = [i for i in ss]  # 生成列表并返回
            print(f"读取到的数据: {l}")
            return l

        except FileNotFoundError:
            print(f"文件 {filename} 未找到")
            return []
        except KeyError:
            print(f"工作表 {stname} 不存在，可用工作表: {wk.sheetnames if wk else '无'}")
            return []
        except Exception as e:
            print(f"文件{filename}处理发生了异常，异常信息是: {e}")
            return []
        finally:
            if wk is not None:
                wk.close()
                print(f"文件{filename}处理结束，工作簿已关闭")
            else:
                print(f"文件{filename}处理结束，工作簿未打开")